import "package:merchants/models/sku.dart";

import "package:merchants/enum/spu_status.dart";

class Spu {
  final String? id; // _id，后端生成
  final List<String> cate;
  final List<String> swiperImages; // swiper_images
  final String coverImage;
  final String name;
  final int priority;
  final List<String>? comment;
  final String detail;
  final List<Sku>? sku;
  final SpuStatus status;

  Spu({
    this.id,
    required this.priority,
    required this.cate,
    required this.swiperImages,
    required this.coverImage,
    required this.name,
    this.comment,
    required this.detail,
    this.sku,
    required this.status,
  });

  factory Spu.fromJson(Map<String, dynamic> json) {
    return Spu(
      id: json['id'] as String? ?? json['_id'] as String?,
      priority: json['priority'] as int? ?? 0,
      cate: (json['cate'] as List<dynamic>?)
              ?.map((item) => item is String ? item : item['_id'] as String)
              .toList() ??
          [],
      swiperImages: (json['swiper_images'] as List<dynamic>?)?.cast<String>() ?? [],
      coverImage: json['cover_image'] as String? ?? '',
      name: json['name'] as String? ?? '',
      comment:
          (json['comment'] as List<dynamic>?)
              ?.map((item) => item is String ? item : item['_id'] as String)
              .toList() ??
          [],
      detail: json['detail'] as String? ?? '',
      sku:
          (json['sku'] as List<dynamic>?)
              ?.map((item) => Sku.fromJson(item as Map<String, dynamic>))
              .toList() ??
          [],
      status: SpuStatus.fromValue(json['status'] as String? ?? 'TO_ENABLE'),
    );
  }

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{
      'priority': priority,
      'cate': cate,
      'swiper_images': swiperImages,
      'cover_image': coverImage,
      'name': name,
      'detail': detail,
      'status': status.value,
    };

    if (id != null) {
      map['id'] = id;
    }
    if (comment != null) {
      map['comment'] = comment!;
    }
    if (sku != null) {
      map['sku'] = sku!.map((skuItem) => skuItem.toJson()).toList();
    }

    return map;
  }
}
